# -*- coding: utf-8 -*-
import redis, odoo, logging

_logger = logging.getLogger(__name__)


class RedisPoolConnection(object):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(RedisPoolConnection, cls).__new__(cls, *args, **kwargs)
        return cls._instance

    def __init__(self):
        self.get_redis_pool()

    def get_redis_pool(self):
        redis_db = self.get_config_value("redis_db") or 0
        redis_host = self.get_config_value("redis_host")
        redis_port = self.get_config_value("redis_port") or "6379"
        self.redis_pool = redis.ConnectionPool(max_connections=120,host=redis_host, port=redis_port, db=redis_db,socket_connect_timeout=1)

    def get_config_value(self, key, default=None):
        return odoo.tools.config.get(key, default)

    def check_redis(self):
        return hasattr(self, "redis_pool")

    def __getattr__(self, item):
        client = redis.StrictRedis(connection_pool=self.redis_pool)
        return getattr(client, item)

    def get_redis_client(self):
        return redis.StrictRedis(connection_pool=self.redis_pool)
